package cn.lu.train.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.Group;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import butterknife.BindView;
import butterknife.OnClick;
import cn.lu.train.R;
import cn.lu.train.base.BaseActivity;
import cn.lu.train.entry.ResultData;
import cn.lu.train.entry.User;
import cn.lu.train.mvp.presenter.user.IMainPresenter;
import cn.lu.train.mvp.view.IMainView;
import cn.lu.train.ui.dialog.GoTipDialog;
import cn.lu.train.ui.dialog.ServiceDialog;
import cn.lu.train.util.LogUtils;
import cn.lu.train.util.ScanHelper;
import cn.lu.train.util.ViewUtils;
import cn.lu.train.util.sysui.StatusBarUtil;

public class MainActivity extends BaseActivity implements IMainView {

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.map_view)
    MapView mapView;
    @BindView(R.id.view_bg)
    View viewBar;

    @BindView(R.id.tv_name)
    TextView mTvName;

    @BindView(R.id.info_bottom)
    Group bottomGroup;

    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private IMainPresenter mainPresenter;

    private PopupWindow popupWindow;
    private boolean isClickMarket;

    BitmapDescriptor bdp = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);

    @Override
    public int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreated() {
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        StatusBarUtil.setTranslucentStatus(this);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) viewBar.getLayoutParams();
        params.topMargin += StatusBarUtil.getStatusBarHeight(this);
        viewBar.setLayoutParams(params);

        View infoView = ViewUtils.inflate(R.layout.dialog_info);
        popupWindow = ViewUtils.getPopupWindow(infoView, -1, -2);
        //popupWindow.setTouchable(false);
        popupWindow.setFocusable(false);
        popupWindow.setOutsideTouchable(false);

        //popupWindow.setFocusable(false);

        /*实例化 定位客户端*/
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                navigateTo(bdLocation);
            }
        });

        mBaiduMap = mapView.getMap();

        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        //设置定位图标是否有箭头
        mBaiduMap.setMyLocationConfiguration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true,null));

        mLocationClient.start();
    }

    /**
     * 将当前位置显示在地图上
     * */
    private void navigateTo(BDLocation location){
       /* if(isFirstLocate){
            *//*获取经纬度*//*
            LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(latLng);
            mBaiduMap.animateMapStatus(update);
            update=MapStatusUpdateFactory.zoomTo(16f);
            mBaiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }*/
        LogUtils.e("--->" + location.getCity());

        /*获取当前位置 并显示到地图上*/
        MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        MyLocationData locationData = locationBuilder.build();
        mBaiduMap.setMyLocationData(locationData);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        isClickMarket = false;
        viewBar.postDelayed(() -> ViewUtils.setViewVisible(bottomGroup, isClickMarket), 300);
        return super.onTouchEvent(event);
    }

    @Override
    public void initData() {
        View child = mapView.getChildAt(1);
        if (child instanceof ImageView || child instanceof ZoomControls) {
            child.setVisibility(View.GONE);
        }

        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                isClickMarket = true;
                LogUtils.e(marker.getPosition().toString());
                //infoDialog.show(getSupportFragmentManager());
                /*mTvName.setText("6店" + marker.getPosition().latitude);
                if (!popupWindow.isShowing()) {
                    popupWindow.showAtLocation(mapView, Gravity.BOTTOM, 0, 0);
                }*/
                ViewUtils.setViewVisible(bottomGroup, true);
                mTvName.setText("6店" + marker.getPosition().latitude);
                return true;
            }
        });

        initOverlay();
    }

    public void initOverlay() {
        LatLng llA = new LatLng(39.963175, 116.400244);
        LatLng llB = new LatLng(39.942821, 116.369199);
        LatLng llC = new LatLng(39.939723, 116.425541);
        LatLng llD = new LatLng(39.906965, 116.401394);

        for (int i = 0; i < 20; i++) {
            /*LatLng ll = new LatLng(39.942821 + i + 50, 116.369199 + i + 50);
            MarkerOptions options2 = new MarkerOptions()
                    .position(ll)
                    .icon(bdp);*/

            //mBaiduMap.addOverlay(options2);
        }

        MarkerOptions options = new MarkerOptions()
                .position(llA)
                .icon(bdp)
                .draggable(true);

        MarkerOptions options2 = new MarkerOptions()
                .position(llB)
                .icon(bdp);

        MarkerOptions options3 = new MarkerOptions()
                .position(llC)
                .icon(bdp);

        MarkerOptions options4 = new MarkerOptions()
                .position(llD)
                .icon(bdp);

        mBaiduMap.addOverlay(options);
        mBaiduMap.addOverlay(options3);
        mBaiduMap.addOverlay(options4);
        mBaiduMap.addOverlay(options2);
    }

    @OnClick({R.id.tv_borrow, R.id.tv_return, R.id.iv_mine, R.id.view_info, R.id.iv_service, R.id.iv_go, R.id.tv_find, R.id.view_drawer})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.tv_borrow:
            case R.id.tv_return:
                new RxPermissions(this)
                        .request(Manifest.permission.CAMERA)
                        .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this)))
                        .subscribe(permission -> {
                            if (permission) {
                                ScanHelper.startQrScan(this, result -> {

                                });
                            } else {
                                Toast.makeText(getBaseContext(), "无使用相机权限", Toast.LENGTH_LONG).show();
                            }
                        });
                break;
            case R.id.iv_mine:
                drawerLayout.openDrawer(Gravity.LEFT);
                break;
            case R.id.iv_service:
                ServiceDialog serviceDialog = new ServiceDialog();
                serviceDialog.show(getSupportFragmentManager());
                break;
            case R.id.tv_find:
                Intent intentNear = new Intent(this, NearByActivity.class);
                startActivity(intentNear);
                break;
            case R.id.iv_go:
                GoTipDialog goTipDialog = new GoTipDialog();
                goTipDialog.setAddressName(mTvName.getText());
                goTipDialog.show(getSupportFragmentManager());
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (bottomGroup.getVisibility() != View.GONE) {
            ViewUtils.setViewVisible(bottomGroup, false);
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onVerifyUser(ResultData<User> data) {
    }

    @Override
    public void onLoading() {

    }

    @Override
    public void onError(Throwable e) {

    }

    @Override
    public void onComplete() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
    }
}